import MobX, {observable as o, computed as c, action as a} from 'mobx';
import _ from 'lodash';
import axios from 'core/axios';
import RootStore from 'core/Store.js';
import request from 'core/request.js';
import Im from 'immutable';
import {browserHistory} from 'react-router';
import html2canvas from 'html2canvas';

class Store extends RootStore {
    constructor(args) {
        super(args);
    }

    will() {

    }

    @o visible = false;
    @o display = 'edit';
    //上传图片
    @o coverFile = {};
    @o newFile = {};
    @o isUpdateCover = false;
    //个人资料
    @o id = '';
    @o nickName = '';
    @o nickNameError = '';
    @o cover = '';
    @o introduce = '';
    @o countries = '';
    @o provinces = '';
    @o city = '';
    @o phone = '';
    @o personalityUrl = '';
    @o personalUrlError = '';
    @o label = '';
    @o type = '';
    @o countryCode = '';
    @o weChatName = '';
    @o password = '';
    @o errorText = '';
    @o passwordError = false;
    @o mobileError = false;
    @o selectCountryCode = {};
    //购买版本记录
    @o buyRecord = [];
    @o versionList = [];
    @o showDialog = false;
    @o versionId = '';
    //二维码
    @o codeList = [];
    @o hasCode = false;
    @o productCode = [];
    @o href = '';//二维码邀请链接
    @o time = '';
    @o productTime = '';
    @o logo = '';
    //邀请
    @o agentList = [];
    @o agentId = '';
    @o agentName = '';
    @o searchName = '';
    @o searchPhone = '';
    @o showSearchFlag = false;


    //关闭用户详情窗口
    @a
    closeDialog(e) {
        e.preventDefault();
        e.stopPropagation();
        this.visible = false;
        this.setToDefault()
    }

    setToDefault() {
        this.display = 'edit';
        this.id = '';
        this.nickName = '';
        this.nickNameError = '';
        this.cover = '';
        this.introduce = '';
        this.countries = '';
        this.provinces = '';
        this.city = '';
        this.phone = '';
        this.personalityUrl = '';
        this.personalUrlError = '';
        this.label = '';
        this.type = '';
        this.countryCode = '';
        this.weChatName = '';
        this.password = '';
        this.errorText = '';
        this.passwordError = false;
        this.mobileError = false;
        this.buyRecord = [];
        this.versionList = [];
        this.showDialog = false;
        this.versionId = '';
        this.codeList = [];
        this.hasCode = false;
        this.productCode = [];
        this.href = '';//二维码邀请链接
        this.time = '';
        this.productTime = '';
        this.logo = '';
        this.coverFile = {};
        this.newFile = {};
        this.isUpdateCover = false;
        this.agentList = [];
        this.agentId = '';
        this.agentName = '';
        this.searchName = '';
        this.searchPhone = '';
        this.showSearchFlag = false;
    }

    //用户信息
    @a
    inputNickName(v) {
        this.nickName = v || '';
    }

    @a
    nickNameBlur() {
        if (!$$.utils.formRegular.nickname(this.nickName) && this.nickName) {
            this.nickNameError = '请输入正确的昵称';
            return;
        }
        this.nickNameError = '';
    }


    @a
    identityChange(value, type) {
        if (this.display === 'edit') {
            this.label = value || '';
        } else {
            this.label = value || '';
            this.type = type || '';
        }

    }

    @a
    personalUrlChange(v) {
        this.personalityUrl = v || '';
    }

    @a
    personalUrlBlur() {
        if (!!this.personalityUrl && ($$.utils.formRegular.number(this.personalityUrl) || /[^\d/a-zA-Z]/g.test(this.personalityUrl))) {
            this.personalUrlError = '仅支持英文或者英文+数字组合';
            return;
        }
        this.personalUrlError = '';
    }

    @a
    countryChange(v) {
        this.countries = v || '';
    }

    @a
    provinceChange(v) {
        this.provinces = v || '';
    }

    @a
    cityChange(v) {
        this.city = v || '';
    }

    @a
    inputIntroduce(v) {
        this.introduce = v || '';
    }

    phoneChange(v) {
        this.phone = v || '';
    }

    mobileBlur() {
        if (this.phone) {
            if ((this.selectCountryCode.code === $$.SEM.CN_COUNTRY_CODE &&
                    $$.utils.formRegular.phone(this.phone)) ||
                (this.selectCountryCode.code !== $$.SEM.CN_COUNTRY_CODE && this.phone.length > 6)) {
                this.mobileError = false;
                this.setErrorText();
            } else {
                this.mobileError = true;
                this.setErrorText();
            }
        } else {
            this.mobileError = false;
            this.setErrorText();
        }
    }

    @a
    inputPassword(v) {
        this.password = v;
    }

    @a
    passwordBlur() {
        if (this.password) {
            if ($$.utils.formRegular.password(this.password)) {
                this.passwordError = false;
                this.setErrorText();
            } else {
                this.passwordError = true;
                this.setErrorText();
            }
        } else {
            this.passwordError = false;
            this.setErrorText();
        }
    }

    setErrorText() {
        let mobileError = !!this.phone ? $$.LN.PLEASE_ENTER_RIGHT_MOBILE : $$.LN.MOBILE_NOT_NULL;
        let passwordError = !!this.password ? $$.LN.PASSWORD_LIMIT_LENGTH : $$.LN.PASSWORD_NOT_NULL;
        this.errorText = this.mobileError ? mobileError : this.passwordError ? passwordError : '';
    }

    copySuccess() {
        this.stores.Message.fire('message', {
            type: $$.SEM.SUCCESS_TEXT,
            text: '复制成功'
        })
    }

    selectCodeItem(item) {
        if (item.code === this.selectCountryCode.code) {
            return;
        }
        this.phone = '';
        this.selectCountryCode = item;
        this.mobileBlur();
    }

    getUserDetail(id) {
        request({
            url: $$.api('getUserDetail'),
            method: 'get',
            data: {
                id: id,
            }
        }).then(res => {
            this.nickName = res.data.nickName || '';
            this.cover = res.data.headPortrait || '';
            this.introduce = res.data.introduce || '';
            this.countries = res.data.countries || '';
            this.provinces = res.data.provinces || '';
            this.city = res.data.city || '';
            this.phone = res.data.phone || '';
            this.personalityUrl = res.data.personalityUrl || '';
            this.label = res.data.label || '';
            this.type = res.data.type || '';
            this.weChatName = res.data.weChatName || '';
        }).catch(err => {
            this.stores.Message.fire('message', {
                type: $$.SEM.ERROR_TEXT,
                text: err.message
            });
        })
    }

    @a
    filesOnChange(e, refs) {
        e.preventDefault();
        let target = e.target;
        let files = target.files;
        this.coverFile = {
            thumb: URL.createObjectURL(files[0]),
            name: $$.utils.getFilename(files[0].name),
            file: files[0]
        };
        if (files[0].size < 1024 * 1024 * $$.SEM.ARTWORK_FILE_SIZE) {
            this.stores.ArtworkEditor.fire('artworkEditor:show', {
                ...this.coverFile, isAvatar: true,
                fileFormat: this.coverFile.file.name.split('.').pop(),
                radio: 1,
            });
        } else {
            this.stores.ConfirmDialog.fire('confirmDialog:show', {
                tips: $$.LN.IMAGE_SIZE_CAN_NOT_OVER_TEN,
                subTips: this.coverFile.name + $$.LN.FILE_SIZE_BIGGER,
                confirmBtnText: $$.LN.I_KNOW,
                hideCancel: true,
            });
        }
        refs.value = '';
    }

    confirmInfo() {
        if (this.isUpdateCover) {
            this.stores.Frame.showLoading();
            request({
                url: $$.api('getPolicy'),
                method: 'get',
                data: {type: 6}
            }).then((res) => {
                //上传需要相关数据
                var {
                    accessid,
                    callback,
                    dir,
                    expire,
                    host,
                    policy,
                    signature,
                    prefix,
                } = res.data;
                //遍历文件数据
                var file = this.newFile;
                var reader = new FileReader();
                //读取文件
                reader.readAsText(file);
                //文件加载成功
                reader.onload = () => {
                    //创建表单数据
                    let formData = new FormData();
                    let md5 = $$.utils.md5(reader.result) + '.' + this.coverFile.file.name.split('.').pop();
                    formData.append('name', this.coverFile.file.name);
                    formData.append('key', encodeURI(dir + prefix + md5));
                    formData.append('policy', policy);
                    formData.append('OSSAccessKeyId', accessid);
                    formData.append('success_action_status', '200');
                    formData.append('callback', callback);
                    formData.append('signature', signature);
                    formData.append('file', file);
                    //开始上传
                    axios.post(host, formData).then((uploadRes) => {
                        if (uploadRes.data.code === $$.SEM.SUCCESS_CODE) {
                            this.updateInfo(uploadRes.data.data.modelCover);
                        } else {
                            this.stores.Frame.hideLoading();
                            this.stores.Message.fire('message', {
                                type: $$.SEM.ERROR_TEXT,
                                text: uploadRes.message
                            });
                        }
                    }).catch((uploadErr) => {
                        this.stores.Frame.hideLoading();
                        this.stores.Message.fire('message', {
                            type: $$.SEM.ERROR_TEXT,
                            text: uploadErr.message
                        });
                    });
                }
            }).catch(err => {
                this.stores.Frame.hideLoading();
                this.stores.Message.fire('message', {
                    type: $$.SEM.ERROR_TEXT,
                    text: err.message
                });
            });
        } else {
            this.updateInfo()
        }
    }

    updateInfo(cover) {
        if (this.display === 'edit') {
            if (!this.nickName || (!!this.nickName && !this.nickName.trim())) {
                this.stores.Message.fire('message', {type: $$.SEM.WARNING_TEXT, text: '昵称不能为空'});
                return;
            }
            if (this.nickNameError) {
                this.stores.Message.fire('message', {type: $$.SEM.WARNING_TEXT, text: '请输入正确的昵称，10个汉字或者20个字符'});
                return;
            }
            if (!!this.personalityUrl && !!this.personalUrlError) {
                this.stores.Message.fire('message', {type: $$.SEM.WARNING_TEXT, text: '个人公开页网址仅支持英文或者英文+数字组合'});
                return;
            }
            request({
                url: $$.api('getUserUpdate'),
                method: 'put',
                data: {
                    id: this.id,
                    nickName: this.nickName,
                    headPortrait: cover || null,
                    introduce: this.introduce,
                    countries: this.countries,
                    provinces: this.provinces,
                    city: this.city,
                    personalityUrl: this.personalityUrl,
                    label: this.label,
                }
            }).then(res => {
                this.stores.Message.fire('message', {type: $$.SEM.SUCCESS_TEXT, text: res.message});
                this.visible = false;
                this.stores.UsersManage.getUsers(1, 20);
                this.setToDefault();
                this.stores.Frame.hideLoading();
            }).catch(err => {
                this.stores.Frame.hideLoading();
                this.stores.Message.fire('message', {
                    type: $$.SEM.ERROR_TEXT,
                    text: err.message
                });
            })
        } else {
            if (this.nickNameError) {
                this.stores.Message.fire('message', {type: $$.SEM.WARNING_TEXT, text: '请输入正确的昵称，10个汉字或者20个字符'});
                return;
            }
            if (!this.nickName || (!!this.nickName && !this.nickName.toString().trim())) {
                this.stores.Message.fire('message', {type: $$.SEM.WARNING_TEXT, text: '昵称不能为空'});
                return;
            }
            if (!this.label || !this.type) {
                this.stores.Message.fire('message', {type: $$.SEM.WARNING_TEXT, text: '请先挑选类型'});
                return;
            }
            if (!this.phone) {
                this.stores.Message.showMessage(3, '手机号不能为空');
                return;
            }
            if (!this.password) {
                this.stores.Message.showMessage(3, '密码不能为空');
                return;
            }
            if(this.errorText){
                this.stores.Message.showMessage(3, '请正确填写信息');
                return;
            }
            request({
                url: $$.api('addNewUsers'),
                method: 'post',
                data: {
                    nickName: this.nickName,
                    password: this.password,
                    phone: this.phone,
                    type: this.type,
                    label: this.type === 4 ? '' : this.label,
                    countryCode: this.selectCountryCode.code,
                }
            }).then(res => {
                this.stores.Message.fire('message', {type: $$.SEM.SUCCESS_TEXT, text: res.message});
                this.visible = false;
                this.stores.UsersManage.getUsers(1, 20);
                this.setToDefault();
            }).catch(err => {
                this.stores.Message.fire('message', {
                    type: $$.SEM.ERROR_TEXT,
                    text: err.message
                });
            })
        }

    }

    confirmUnBind(id) {
        console.log(this.id);
        this.stores.Frame.showLoading();
        request({
            url: `${$$.api('unbindWeChat')}?id=${id}`,
            method: 'put',
        }).then(res => {
            this.stores.Frame.hideLoading();
            this.weChatName = '';
        }).catch(err => {
            this.stores.Frame.hideLoading();
            this.stores.Message.fire('message', {type: $$.SEM.ERROR_TEXT, text: err.message});
        });
    }

    unbindWeixin() {
        this.stores.ConfirmDialog.fire('confirmDialog:show', {
            tips: $$.LN.CONFIRM_TO_UNBIND_WECHAT,
            func: () => {
                this.confirmUnBind(this.id)
            }
        });
    }


    //版本记录及有效期
    @a
    getRecords(id) {
        request({
            url: $$.api('getUserRecords') + id,
        }).then(res => {
            this.buyRecord = res.data;
        }).catch(err => {
            this.stores.Message.fire('message', {
                type: $$.SEM.ERROR_TEXT,
                text: err.message
            });
        })
    }

    getProductList() {
        request({
            url: $$.api('getProductList'),
            method: 'get',
        }).then(res => {
            res.data.map(i => {
                if (i.time === 12) {
                    this.versionList.push({value: i.id, label: i.name + '1年'});
                } else if (i.time === 24) {
                    this.versionList.push({value: i.id, label: i.name + '2年'});
                } else {
                    this.versionList.push({value: i.id, label: i.name + '3年'});
                }
            });
        }).catch(err => {
            this.stores.Message.fire('message', {
                type: $$.SEM.ERROR_TEXT,
                text: err.message
            });
        })
    }

    addVersionRecord(e) {
        e.preventDefault();
        e.stopPropagation();
        this.showDialog = true;
    }

    closeVersionDialog() {
        this.showDialog = false;
        this.versionId = '';
    }

    versionChoose(id, name) {
        this.versionId = id || '';
    }

    confirmAddRecord() {
        if (!this.versionId) {
            this.stores.Message.showMessage(3, '请先选择版本');
            return;
        }
        request({
            url: $$.api('addVersionRecord'),
            method: 'post',
            data: {
                productId: this.versionId,
                userId: this.id,
            }
        }).then(res => {
            this.stores.Message.fire('message', {type: $$.SEM.SUCCESS_TEXT, text: res.message});
            this.getRecords(this.id);
            this.showDialog = false;
            this.versionId = '';
        }).catch(err => {
            this.stores.Message.fire('message', {
                type: $$.SEM.ERROR_TEXT,
                text: err.message
            });
        })
    }

    //二维码
    getProductCode(id) {
        request({
            url: $$.api('getProductCode') + id,
        }).then(res => {
            if (res.data) {
                this.hasCode = true;
                this.codeList = JSON.parse(res.data.productInfo);
                this.productTime = this.codeList[0].time;
            } else {
                this.hasCode = false;
            }
        }).catch(err => {
            this.stores.Message.showMessage(2, err.message);
        })
    }

    itemClick(item, exist) {
        let prefix = global.window.location.origin.indexOf('manage-test') > -1 ? 'https://staging.artivr.com' : 'https://www.artivr.com';
        if (exist) {
            this.productCode = this.productCode.filter((i) => {
                return i !== item.productCode;
            });
        } else {
            this.productCode.push(item.productCode);
        }
        if (this.productCode.length === 0) {
            this.href = `${prefix}/?invite=${this.id}&validity=${this.time}`;
        } else if (this.productCode.length === 1) {
            this.href = `${prefix}/?invite=${this.id}&validity=${this.time}&productCode=${this.productCode.toString(this.productCode)}`;
        } else {
            this.href = `${prefix}/?invite=${this.id}&validity=${this.time}&productCode=${this.productCode.join(',')}`;
        }
        console.log('this.href1', this.href)
    }

    clickBtn() {
        if (this.hasCode) {
            this.updateProductVersion()
        } else {
            this.addProductVersion()
        }
    }

    productTimeChange(v) {
        this.productTime = v || '';
    }

    updateProductVersion() {
        if (!this.productTime) {
            this.stores.Message.showMessage(3, '赠送时长不能为空');
            return;
        }
        request({
            url: $$.api('getProductUpdate'),
            method: 'put',
            data: {
                orgId: this.id,
                time: this.productTime,
            }
        }).then(res => {
            this.stores.Message.fire('message', {type: $$.SEM.SUCCESS_TEXT, text: res.message});
            this.getProductCode(this.id);
            this.productCode = [];
        }).catch(err => {
            this.stores.Message.fire('message', {
                type: $$.SEM.ERROR_TEXT,
                text: err.message
            });
        })
    }


    deleteProductVersion() {
        request({
            url: $$.api('getProductDelete') + this.id,
            method: 'delete',
        }).then(res => {
            this.stores.Message.fire('message', {type: $$.SEM.SUCCESS_TEXT, text: res.message});
            this.productTime = '';
            this.getProductCode(this.id);
        }).catch(err => {
            this.stores.Message.fire('message', {
                type: $$.SEM.ERROR_TEXT,
                text: err.message
            });
        })
    }

    addProductVersion() {
        if (!this.productTime) {
            this.stores.Message.showMessage(3, '赠送时长不能为空');
            return;
        }
        request({
            url: $$.api('addProductVersion'),
            method: 'post',
            data: {
                orgId: this.id,
                time: this.productTime,
            }
        }).then(res => {
            this.stores.Message.fire('message', {type: $$.SEM.SUCCESS_TEXT, text: res.message});
            this.getProductCode(this.id);
        }).catch(err => {
            this.stores.Message.fire('message', {
                type: $$.SEM.ERROR_TEXT,
                text: err.message
            });
        })
    }

    savePicture() {
        setTimeout(() => {
            html2canvas(document.querySelector('#content')).then(canvas => {
                let imgURL = canvas.toDataURL();
                let a = document.createElement('a');
                // document.body.appendChild(canvas);
                a.href = imgURL;
                a.download = '邀请码';
                a.click();
            });
        }, 20);
    }

    drawImage() {
        let count = 0;
        let image = new Image();
        let prefix = global.window.location.origin.indexOf('manage-test') > -1 ? 'https://staging.artivr.com' : 'https://www.artivr.com';
        image.onload = () => {
            const c = document.createElement('canvas');

            c.width = image.naturalWidth;
            c.height = image.naturalHeight;

            const cxt = c.getContext('2d');

            cxt.drawImage(image, 0, 0);
            // 得到图片的base64编码数据
            this.header = c.toDataURL();
        };


        let logo = new Image();
        logo.onload = () => {
            const c = document.createElement('canvas');

            c.width = logo.naturalWidth;
            c.height = logo.naturalHeight;

            const cxt = c.getContext('2d');

            cxt.drawImage(logo, 0, 0);
            // 得到图片的base64编码数据
            this.logo = c.toDataURL();
            let a = document.getElementById('codeImg');
            setTimeout(() => {
                if (a) {
                    if (a.style['z-index'] === '1') {
                        a.style['z-index'] = '1';
                    } else {
                        a.style['z-index'] = '2';
                    }
                }
            }, 20);
        };
        logo.src = decodeURIComponent(prefix + '/assets/images/components/services/UsersEdit/images/logo.png');
    }

    //邀请
    getAgentInfo() {
        request({
            url: $$.api('getAgentInfo'),
            method: 'get',
            data:{
                phone:this.searchPhone || null,
                name:this.searchName || null,
            }
        }).then(res => {
            this.agentList = res.data;
        }).catch(err => {
            this.stores.Message.showMessage(2, err.message);
        })
    }

    getAgentName(){
        request({
            url:$$.api('getAgentName') + this.id
        }).then(res => {
            if(res.data){
                this.agentName = res.data.nickName;
                this.agentId = res.data.id;
            }
        }).catch(err => {
            this.stores.Message.showMessage(2, err.message);
        })
    }

    deleteAgent(){
        request({
            url:$$.api('deleteAgent') + this.id,
            method:'delete',
        }).then(res => {
            this.stores.Message.showMessage(1, '删除成功');
            this.agentName = '';
            this.agentId = '';
        }).catch(err => {
            this.stores.Message.showMessage(2, err.message);
        })
    }

    authorNameFocus(){
        this.showSearchFlag = true;
        this.getAgentInfo()
    }
    closeSearchWrapper() {
        this.showSearchFlag = false;
    }
    searchPhoneOnChange(v){
        this.searchPhone = v || '';
    }
    searchNameOnChange(v){
        this.searchName = v || '';
    }

    search(){
        this.getAgentInfo()
    }

    closePhoneHandle(){
        this.searchPhone = '';
        this.getAgentInfo()
    }

    closeNameHandle(){
        this.searchName = '';
        this.getAgentInfo()
    }

    itemSearchClick(e,data){
        this.agentId = data.id;
        this.agentName = data.name;
        this.showSearchFlag = false;
    }
    @a
    nameInput(e) {
        if (e.which === 13) {
            this.search();
        }
    }

    confirmAddAgent() {
        if (!this.agentId) {
            this.stores.Message.showMessage(3, '请先选择代理商');
            return;
        }
        request({
            url: $$.api('addAgentUser'),
            method: 'post',
            data: {
                inviteId: this.agentId,
                userId: this.id,
            }
        }).then(res => {
            this.stores.Message.fire('message', {type: $$.SEM.SUCCESS_TEXT, text: res.message});
            this.showSearchFlag = false;
        }).catch(err => {
            this.stores.Message.fire('message', {
                type: $$.SEM.ERROR_TEXT,
                text: err.message
            });
        })
    }


    mount() {
        let prefix = global.window.location.origin.indexOf('manage-test') > -1 ? 'https://staging.artivr.com' : 'https://www.artivr.com';
        this.on('usersedit:show', (data) => {
            this.display = data.display || '';
            if (this.display === 'edit') {
                this.id = data.detail.id;
                this.type = data.detail.type || '';
                // this.label = data.detail.label || '';
                this.getRecords(this.id);
                this.getProductCode(this.id);
                this.getUserDetail(this.id);
                this.getProductList();
                this.getAgentName();
                if (this.type === 2) {
                    this.time = new Date().getTime() + $$.SEM.QRCODE_OVER_TIME * 86400000;
                    this.href = `${prefix}/?invite=${this.id}&validity=${this.time}`;
                    console.log('this.href', this.href)
                }
            }
            this.visible = true;
            this.isUpdateCover = false;
        });
        this.stores.ArtworkEditor.on('artworkEditor:avatar', (data) => {
            this.cover = data.img;
            this.isUpdateCover = true;
            this.newFile = $$.utils.dataURLtoBlob(data.img);
        });
        this.stores.ArtworkEditor && this.stores.ArtworkEditor.on('usersEdit:reUpload', (data) => {
            if (data) {
                this.filesOnChange(data.e, data.ref);
            }
        });

        browserHistory.listen(() => {
            if (this.visible) {
                this.visible = false;
                this.setToDefault()
            }
        });

    }

}

export default Store;